﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.IO;
using Common;

public partial class website_admin_sales_ordersettings : PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Expires = -1;
        PageBegin();
        switch (RequestBase.GetFormString("otype"))
        {
            case "sendshipmentnotice":
                SendShipmentNotice();
                break;
            case "loadingshipmentlist":
                LoadShipmentList();
                break;
        }

        if (!IsPostBack)
        {
            if (Utils.IsGuid(RequestBase.GetQueryString("objectid")))
            {
                InitializeOrderObj();
            }
        }
    }
    void InitializeOrderObj()
    {
        string result = "";
        Model.OrderBase _order = BLL.OrderBase.GetObjectById(RequestBase.GetQueryString("objectid"), out result);

        if (_order != null)
        {
            txtOrderNumber.Value = _order.OrderNumber;
            txtPhone.Value = _order.ShipMobile;
            txtPhoneNumbers.Value = _order.ShipMobile;
            Model.MembershipBase _member = BLL.MembershipBase.GetObjById(_order.UserId);
            txtEmail.Value = _member.Email;
            txtNoticeContent.Value = string.Format("您的积分兑换订单{0}兑换的商品已发货，快递单号：expressnumber，快递公司为：express，预计2日后到达，收件人为{1}，收件人联系电话{2}，请注意查收。", _order.OrderNumber, _order.ShipToName, _order.ShipTel);
            txtShipmentDate.Value = DateTime.Now.ToString("yyyy-MM-dd");

            lblOrderNumber.Text = _order.OrderNumber;
            lblOrderDate.Text = _order.OrderDate.ToString("yyyy-MM-dd");
            lblTotalPrice.Text = _order.TotalPrice.ToString();
            lblTotalPrice.Text = _order.TotalPrice.ToString();
            emTotalCost.InnerText = _order.TotalPrice.ToString();
            lblShipAddress.Text = _order.ShipAddress;
            lblShipMobile.Text = _order.ShipMobile;
            lblShipTel.Text = _order.ShipTel;
            lblShipToName.Text = _order.ShipToName;
            lblShipZip.Text = _order.ShipZip;
            lblShipCounties.Text = _order.ShipState + "．" + _order.ShipCity + "．" + _order.ShipCounties;

            lblOrderStatus.Text = _order.StatusCode.ToString().Replace("-1", "已作废").Replace("0", "未支付").Replace("1", "已兑换").Replace("2", "已发货");

            rptOrderItems.DataSource = BLL.OrderBase.GetItems(RequestBase.GetQueryString("objectid"), out result);
            rptOrderItems.DataBind(); 
        }
    }

    #region 发送快递信息
    void SendShipmentNotice()
    {
        Model.ShipmentProgressBase _obj = new Model.ShipmentProgressBase();
        _obj.Notice = "保单快递通知";
        _obj.NoticeType = RequestBase.GetFormString("noticetype");
        _obj.NoticeContent = RequestBase.GetFormString("noticecontent").Replace("expressnumber", RequestBase.GetFormString("shipmentnumber")).Replace("express", RequestBase.GetFormString("shipmenttype"));
        _obj.ShipmentNumber = RequestBase.GetFormString("shipmentnumber");
        _obj.ShipmentDate = DateTime.Parse(RequestBase.GetFormString("shipmentdate"));
        _obj.ShipmentType = RequestBase.GetFormString("shipmenttype");
        _obj.Email = RequestBase.GetFormString("email");
        _obj.Phone = RequestBase.GetFormString("phone"); 
        _obj.StatusCode = 0;
        _obj.RegardingObjectId = RequestBase.GetFormString("objectid");
        _obj.RegardingObjectName = "积分兑换订单快递信息发送";
        _obj.ProgressName = string.Format("积分兑换订单[{0}]快递发送提醒", RequestBase.GetFormString("ordernumber"));

        string res = (new BLL.ShipmentProgressBase()).Add(_obj);
        if (res.IndexOf("succeeded") >= 0)
        {
            string shipmentprogressid = res.Split('|')[1];
            try
            {
                if (_obj.NoticeType.IndexOf("1") >= 0)
                {
                    string recitemslist = SmtpMail.EmailFactory.MailToGroup(
                        new string[] { RequestBase.GetFormString("email") },
                        null,
                        "www.mapfre-assistance.com.cn",
                        ConfigurationManager.AppSettings["Email"].ToString(),
                        ConfigurationManager.AppSettings["EmailPassword"].ToString(),
                        _obj.ProgressName,
                        _obj.NoticeContent,
                        ConfigurationManager.AppSettings["SmtpServer"].ToString(),
                        25);
                    res = "succeeded";
                }

                if (res.IndexOf("succeeded") >= 0)
                {
                    if (_obj.NoticeType.IndexOf("2") >= 0)
                    {
                        sms_webservice.SmsWebService _wbss = new sms_webservice.SmsWebService();
                        sms_webservice.SmsMessage _smsObj = new sms_webservice.SmsMessage();
                        _smsObj.PhoneNumbers = _obj.Phone.Split(',');
                        _smsObj.OrderNumber = RequestBase.GetFormString("ordernumber");
                        _smsObj.SmsContent = _obj.NoticeContent;
                        _smsObj.CreatedBy = new Guid(this.SystemUserId);
                        _smsObj.SmsId = "";

                        _obj.StatusCode = (new sms_webservice.SmsWebService().SendSMS(_smsObj).Trim().ToLower() == "failed") ? -1 : 1;
                        res = (_obj.StatusCode == 1) ? "succeeded" : "发送失败！";
                    }
                    else
                    {
                        _obj.StatusCode = 1;
                        res = "succeeded";
                    }

                    _obj.ShipmentProgressId = shipmentprogressid;
                    (new BLL.ShipmentProgressBase()).Update(_obj);
                    BLL.OrderBase.UpdateStatus(RequestBase.GetFormString("ordernumber"), this.SystemUserId, 2);
                }
            }
            catch (Exception err)
            {
                res = err.Message;
            }
        }
        BLL.AjaxHelper.ResponseWrite(res);
    }
    void LoadShipmentList()
    {
        try
        {
            string SQL = " AND RegardingObjectId = '" + RequestBase.GetFormString("objectid") + "'";

            Control uc_rep = LoadControl("~/website_admin/insurance/_controls/ctlOrderList.ascx");

            Repeater rptShipmentList = (Repeater)uc_rep.FindControl("rptShipmentList");

            DataTable dat = BLL.CommonBLL.Select("ShipmentProgressBase", "*", SQL + " ORDER BY ShipmentDate ASC");

            rptShipmentList.DataSource = dat;
            rptShipmentList.DataBind();

            StringBuilder strb = new StringBuilder();
            StringWriter sw = new StringWriter(strb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            rptShipmentList.RenderControl(htw);

            BLL.AjaxHelper.ResponseWrite(strb.ToString());
        }
        catch (System.Threading.ThreadAbortException err)
        {
            //nothing   to   do   
        }
        catch (Exception err)
        {
            BLL.AjaxHelper.ResponseWrite(err.Message);
        }
    }
    #endregion
}
